package com.drinks.yiniang.ui.activity.user.points;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.drinks.yiniang.R;
import com.drinks.yiniang.adapter.user.points.PointsExchangeAdapter;
import com.drinks.yiniang.common.recycler.decoration.ItemSpacesDecoration;
import com.drinks.yiniang.entity.common.AdBannerEntity;
import com.drinks.yiniang.entity.user.points.PointsExchangeJson;
import com.drinks.yiniang.io.api.CouponApiIO;
import com.drinks.yiniang.utils.ActivityUtils;
import com.drinks.yiniang.utils.GlideUtils;
import com.drinks.yiniang.utils.ToastUtils;
import com.hansen.library.entity.BaseJson;
import com.hansen.library.io.tuple.Tuple2;
import com.hansen.library.listener.APIRequestCallback;
import com.hansen.library.ui.widget.image.RatioRoundImageView;
import com.drinks.yiniang.ui.widget.recycler.BaseRecyclerView;
import com.hansen.library.Constants;
import com.hansen.library.listener.OnSureCancelListener;
import com.hansen.library.ui.activity.BaseTranBarActivity;
import com.hansen.library.listener.OnNavgationBarClickListener;
import com.hansen.library.ui.widget.dialog.Material2Dialog;
import com.hansen.library.ui.widget.nav.NavigationBarLayout;
import com.hansen.library.utils.ScreenSizeUtils;
import com.hansen.library.utils.StringUtils;

import java.util.ArrayList;

/**
 * 积分兑换页面
 *
 * @author han
 * @date 2019/09/08
 */
public class PointsExchangeActivity extends BaseTranBarActivity implements OnNavgationBarClickListener,
        BaseQuickAdapter.OnItemClickListener, OnSureCancelListener {

    //nav
    private NavigationBarLayout nav_bar_points_exchange;
    //总积分
    private TextView tv_points_exchange_total;
    //列表
    private BaseRecyclerView rcv_points_exchange;
    //积分广告位
    private RatioRoundImageView iv_points_exchange_ad;

    private PointsExchangeAdapter mExchangeAdapter;

    private Material2Dialog mDialog;

    //广告
    private AdBannerEntity mBanner;

    //总的积分
    private String mTotalPoints;

    @Override
    protected void initView() {
        nav_bar_points_exchange = findViewById(R.id.nav_bar_points_exchange);

        rcv_points_exchange = findViewById(R.id.rcv_points_exchange);

        iv_points_exchange_ad = findViewById(R.id.iv_points_exchange_ad);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        mContext = this;

        initAdapter();
        getCouponList();
    }

    private void initAdapter() {
        rcv_points_exchange.setLayoutManager(new LinearLayoutManager(mContext));
        rcv_points_exchange.addItemDecoration(ItemSpacesDecoration.getLRBItemCountDPDecoration(10));

        mExchangeAdapter = new PointsExchangeAdapter(mContext, new ArrayList<PointsExchangeJson.PointsExchangeList>());
        mExchangeAdapter.addHeaderView(getHeaderView());
        mExchangeAdapter.setHeaderAndEmpty(true);
        mExchangeAdapter.setCenterEmpty(getLayoutInflater(), rcv_points_exchange);
        mExchangeAdapter.bindToRecyclerView(rcv_points_exchange);
    }

    //获取header
    private View getHeaderView() {
        View mHeaderView = getLayoutInflater().inflate(R.layout.header_points_exchange, (ViewGroup) rcv_points_exchange.getParent(), false);

        tv_points_exchange_total = mHeaderView.findViewById(R.id.tv_points_exchange_total);

        return mHeaderView;
    }

    @Override
    protected void initListener() {
        nav_bar_points_exchange.setOnNavgationBarClickListener(this);
        iv_points_exchange_ad.setOnClickListener(this);

        mExchangeAdapter.setOnItemClickListener(this);
    }

    @Override
    public void widgetClick(View v) {
        switch (v.getId()) {
            case R.id.iv_points_exchange_ad://广告位
                if (mBanner == null) {
                    return;
                }

                ActivityUtils.startActivityByAdType(mContext, mBanner.getType(), mBanner.getValue());
                break;
            default:
                break;
        }
    }

    @Override
    public int getTranBarResID() {
        return R.layout.activity_points_exchange;
    }

    @Override
    public void onBackClick(View v) {
        finish();
    }

    @Override
    public void onEditClick(View v) {

    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        PointsExchangeJson.PointsExchangeList data = mExchangeAdapter.getItem(position);

        if (data == null) {
            return;
        }

        initDialog(data.getId(), data.getCost_points(), data.getAmount());
    }

    @Override
    public void onSure(int type, String value) {
        doExchange(value);
    }

    @Override
    public void onCancel(int type) {

    }

    private void initDialog(String couponId, String pointsValue, String couponValue) {
        if (!StringUtils.judgeGreaterEqualNumber(mTotalPoints, pointsValue)) {
            ToastUtils.showShort(getString(R.string.text_points_not_enough));
            return;
        }
        StringBuilder builder = new StringBuilder("使用");
        builder.append(StringUtils.getNullEmptyConvert__(pointsValue));
        builder.append("积分兑换\n");
        builder.append(StringUtils.getNullEmptyConvert__(couponValue));
        builder.append("元优惠券");

        mDialog = Material2Dialog.newInstance(null, builder.toString(), couponId, true);

        mDialog.show(getSupportFragmentManager(), Constants.TAG_TIPS_DIALOG);
    }

    //兑换
    private void doExchange(String couponId) {
        if (StringUtils.isEmpty(couponId)) {
            return;
        }

        showLoadingDialog();

        CouponApiIO.getInstance().doExchangeCoupon(couponId, new APIRequestCallback<BaseJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(BaseJson res) {
                getCouponList();
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    private void getCouponList() {
        showLoadingDialog();

        CouponApiIO.getInstance().getCouponExchangeList(new APIRequestCallback<PointsExchangeJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(PointsExchangeJson res) {
                if (mExchangeAdapter == null) {
                    return;
                }

                setData(res.getData());

                mExchangeAdapter.getData().clear();
                mExchangeAdapter.addData(res.getData().getCoupons());
                mExchangeAdapter.loadMoreEnd();
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
                mExchangeAdapter.loadMoreFail();
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    private void setData(PointsExchangeJson.PointsExchangeData data) {
        mTotalPoints = data.getMy_points();

        tv_points_exchange_total.setText(String.format(mContext.getString(R.string.text_your_points_format), StringUtils.getNullEmptyConvertZero(mTotalPoints)));

        FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) rcv_points_exchange.getLayoutParams();

        mBanner = data.getBanner();

        if (mBanner != null) {
            iv_points_exchange_ad.setVisibility(View.VISIBLE);
            params.bottomMargin = (int) (ScreenSizeUtils.getDisplayWidth(mContext) * 0.254);
            GlideUtils.loadExchangeAdList(mContext, iv_points_exchange_ad, mBanner.getCover_url());
        } else {
            iv_points_exchange_ad.setVisibility(View.GONE);
            params.bottomMargin = 0;
        }
    }
}
